/*
io.c
offer agv board io config and driver
designed by lunanting

------------------------------
2020-05-24 15:42:22
create file
------------------------------
*/

#include "io.h"
#ifdef WASHER_MERGE
#include "../bsp/io_config.h"

#else
#include "../../board/ok1053a/board/board.h"
#endif
#include "../bsp/bsp.h"

/*
agv io config and init
*/
void xp_agv_io_init(u8 default_state){
    #ifdef WASHER_MERGE


    #else
    gpio_dev_t gpio;
    static u8 init=0;
    if(init==1)return;
    gpio.config=OUTPUT_PUSH_PULL;
    gpio.priv=NULL;
    for(u8 i=PORT_GPIO_DO_1;i<8;i++){
        gpio.port=i;
        xp_io_init(&gpio,"DO",i+1);
        xp_agv_io_set(i+1,default_state);
    }
    gpio.config=INPUT_PULL_UP;
    gpio.priv=NULL;
    for(u8 i=PORT_GPIO_DI_1;i<PORT_GPIO_EM_STOP;i++){
        gpio.port=i;
        xp_io_init(&gpio,"DI",i+1);
    }
    println("AGV board io init complete !");
    init =1;
    #endif
}





/*
agv board set DO
param:
    num:borad DO pin num,1~8 or 1~24
    state:io state,1=high
*/
void xp_agv_io_set(const u8 num,u8 state){
    #ifdef WASHER_MERGE
    if(num<1||num>24){
        perr("num range fault! need to be [1~24]");
    }
    xp_io_write_pin(1,num-1,state);


    #else
    gpio_dev_t gpio;

    if(num<1||num>8){
        println("io set num error!num=%d",num);
        return;
    }
    gpio.port=PORT_GPIO_DO_1+num-1;
    gpio.config=OUTPUT_PUSH_PULL;
    gpio.priv=NULL;
    if(state==0){
        hal_gpio_output_low(&gpio);
    }
    else{
        hal_gpio_output_high(&gpio);
    }
    #endif
}


/*
agv board DI io read
param:
    num:board DI num,1~8 or 1~24
return:io state
*/
int xp_agv_io_read(const u8 num){
    #ifdef WASHER_MERGE
    if(num<1||num>24){
        perr("num range fault! need to be [1~24]");
    }
    xp_io_read_input_pin(1,num-1);

    #else
    gpio_dev_t gpio;
    u32 state=0;

    if(num<1||num>8){
        println("io set num error!num=%d",num);
        return 0;
    }
    gpio.port=PORT_GPIO_DI_1+num-1;
    gpio.config=INPUT_PULL_UP;
    gpio.priv=NULL;
    hal_gpio_input_get(&gpio,&state);
    return state;
    #endif
}

/************************io test**********************/
/*
agv gpio  test
*/
int xp_agv_io_debug(char *type,char *fun,char *param){
    int pin;
    if(strcmp(type,"agv_io")!=0)return 0;
    if(strcmp(fun,"read")==0){
        pin=atoi(param);
        println("agv io input %d pin:%d",pin,xp_agv_io_read(pin));
    }
    else if(strcmp(fun,"set_pin")==0){
        pin=atoi(param);
        xp_agv_io_set(pin,1);
    }
    else if(strcmp(fun,"reset_pin")==0){
        pin=atoi(param);
        xp_agv_io_set(pin,0);
    }

    else{
        return 0;
    }
    return 1;
}



//end of the file
